package com.yiqi.news.mvp.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.transition.Visibility
import android.view.View
import butterknife.OnClick

import com.jess.arms.base.BaseActivity
import com.jess.arms.di.component.AppComponent
import com.jess.arms.utils.ArmsUtils
import com.trello.rxlifecycle2.android.RxLifecycleAndroid
import com.yiqi.huize.mvp.dialog.OpenPageDialog
import com.yiqi.news.Constant

import com.yiqi.news.di.component.DaggerLoginComponent
import com.yiqi.news.di.module.LoginModule
import com.yiqi.news.mvp.contract.LoginContract
import com.yiqi.news.mvp.presenter.LoginPresenter

import com.yiqi.news.R
import com.yiqi.news.app.service.UserController
import com.yiqi.news.app.widget.qmui.QMUITipDialog
import com.yiqi.news.entity.User
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_login.*
import java.util.concurrent.TimeUnit

class LoginActivity : BaseActivity<LoginPresenter>(), LoginContract.View, View.OnFocusChangeListener, TextWatcher, OpenPageDialog.OnClickListener {
    override fun showMobileError(msg: String) {
        tv_show_mobile_error.visibility = View.VISIBLE
        tv_show_mobile_error.text = msg
    }


    override fun showLoginError(msg: String) {
        tv_show_code_error.visibility = View.VISIBLE
        tv_show_code_error.text = msg
    }


    override fun showUnBind() {
        var bundle = Bundle()
        bundle.putString("mobile", edt_login_phone.text.toString())
        bundle.putString("code", edt_login_code.text.toString())
        ArmsUtils.startActivity(this, CodeActivity::class.java, bundle)
    }

    override fun showLoginSuccess(user: User) {
        UserController.getInstance().saveLoginResultCache(user)
        ArmsUtils.hidekeyboardFinish(this)
        ArmsUtils.startActivity(MainActivity::class.java)
    }

    override fun showCodeSuccess() {
        tv_show_mobile_error.visibility = View.GONE
        codeSuccess()

    }

    override fun onOpen() {
        ArmsUtils.startActivity(BindMobileActivity::class.java)
    }

    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .loginModule(LoginModule(this))
                .build()
                .inject(this)
    }


    override fun initView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_login //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }


    override fun initData(savedInstanceState: Bundle?) {
        edt_login_phone.onFocusChangeListener = this
        edt_login_code.onFocusChangeListener = this

        edt_login_phone.addTextChangedListener(this)
        edt_login_code.addTextChangedListener(this)
    }

    override fun onFocusChange(view: View?, hasFocus: Boolean) {
        when (view?.id) {
            R.id.edt_login_phone -> if (hasFocus) view_login_phone.setBackgroundColor(ArmsUtils.getColor(this, R.color.color_A22217)) else view_login_phone.setBackgroundColor(ArmsUtils.getColor(this, R.color.color_CCCCCC))
            R.id.edt_login_code -> if (hasFocus) view_login_code.setBackgroundColor(ArmsUtils.getColor(this, R.color.color_A22217)) else view_login_code.setBackgroundColor(ArmsUtils.getColor(this, R.color.color_CCCCCC))
        }
    }


    @OnClick(R.id.btn_login_agreement, R.id.btn_login_code, R.id.btn_login, R.id.btn_login_wechat, R.id.btn_login_weibo, R.id.btn_login_qq, R.id.btn_login_close)
    fun onClick(view: View) {
        when (view.id) {
            R.id.btn_login_agreement -> {
                var bundle = Bundle()
                bundle.putBoolean("is_agg", true)
                ArmsUtils.startActivity(this, AgreementActivity::class.java, bundle)
            }
            R.id.btn_login_code -> sendCode()
            R.id.btn_login -> {
                mPresenter?.login(edt_login_phone.text.toString().trim(), edt_login_code.text.toString().trim())
            }
            R.id.btn_login_wechat -> openPage(Constant.WE_CHAT)
            R.id.btn_login_weibo -> openPage(Constant.WEIBO)
            R.id.btn_login_qq -> openPage(Constant.QQ)
            R.id.btn_login_close -> killMyself()
        }
    }

    private fun sendCode() {
        mPresenter?.sendCode(edt_login_phone.text.toString().trim())
    }

    @SuppressLint("CheckResult")
    private fun codeSuccess() {
        mQMUIInfoDialog.show()
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleAndroid.bindActivity(provideLifecycleSubject()))
                .map {
                    60 - it
                }
                .take((60 + 1).toLong())
                .doFinally {
                    btn_login_code.isEnabled = true
                    btn_login_code.text = "获取验证码"
                }.subscribe { aLong ->
                    btn_login_code.isEnabled = false
                    btn_login_code.text = aLong!!.toString() + "s"
                }
    }

    override fun showMessage(message: String) {
        ArmsUtils.snackbarText(message)
    }

    override fun launchActivity(intent: Intent) {
        ArmsUtils.startActivity(intent)
    }

    override fun killMyself() {
        finish()
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

    }

    override fun afterTextChanged(s: Editable?) {
        if (edt_login_phone.text.isNotEmpty() && edt_login_code.text.isNotEmpty()) btn_login.isEnabled = true else false
    }


    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar.titleBar(R.id.tool_login).init()
    }

    private var mLoginType: Int = 0
    private val mQMUIInfoDialog: QMUITipDialog by lazy {
        return@lazy QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                .setTipWord(getString(R.string.dialog_code_send_success))
                .create()
    }
    private val mOpenPageDialog by lazy {
        return@lazy OpenPageDialog(this)
    }


    private fun openPage(type: Int) {
        mLoginType = type
        when (type) {

            Constant.WE_CHAT -> {
                mOpenPageDialog.setDesc("\"NewsApp\"想要打开微信")
            }
            Constant.WEIBO -> {
                mOpenPageDialog.setDesc("\"NewsApp\"想要打开微博")
            }
            Constant.QQ -> {
                mOpenPageDialog.setDesc("\"NewsApp\"想要打开QQ")
            }
        }

//        mOpenPageDialog.show()
//        mOpenPageDialog.setOnClickListener(this)
    }


}
